import socket
import random
from typing import Dict, List, Union

with open('IPs.txt', 'r') as f:
    IPs = f.readlines()
    IPs = [i.strip(' \n') for i in IPs]


def PingTest(ip: str, port: int) -> bool:
    socket.setdefaulttimeout(1)
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    try:
        s.connect((ip, port))
        s.shutdown(1)
        return True
    except socket.timeout:
        return False
    # except:
    #     return False


def AvailableIPList() -> List[str]:
    ret = []
    for i in IPs:
        ip, port = tuple(i.split(':'))
        if PingTest(ip, int(port)) is True:
            ret.append(i)
    return ret


def GetRandProxy(cur_proxy: str) -> Union[None, Dict[str, str]]:
    src = IPs
    if not src:
        return None
    elif cur_proxy is None:
        ret = src[random.randint(0, len(src))]
        # ip, port = tuple(ret.split(':'))
    else:
        ret = cur_proxy
        while ret == cur_proxy:
            ret = src[random.randint(0, len(src))]

    return {'https': ret}
